<?php
/**
 * 
 * @authors Liujinbi (857053791@QQ.com)
 * @date    2017-08-03 15:11:12
 * @version $Id$
 */

namespace app\mall\controller;

use think\Request;
use think\Db;
use think\Session;
use think\Config;

class Cart extends Base
{	
	/**
	 * 购物车数据
	 * @return [type] [description]
	 */
	public function index(){
		$uid = $this->uid;
		if (!$uid) {
			$this->success('success','',[]);
		}
		$list = Db::field('g.*,sval.*,c.*')
		->table('sdzx_goods')->alias('g')
		->join('sdzx_goods_specval sval','g.goods_id=sval.goods_id')
		->join('sdzx_user_cart c','sval.specval_id=c.specval_id and sval.goods_id=c.goods_id')
		->where("c.user_id={$uid} and c.addbyagent=0")
		->select();

		$this->success('success','',$list);
	}

	/**
	 * 添加商品
	 */
	public function edit()
	{
		$uid = $this->uid;
		$goods_id = Request()->param('goods_id','');
		$specval_id = Request()->param('specval_id','');
		$num = Request()->param('num');
		if (empty($goods_id) || empty($specval_id)) {
			$this->error('缺少参数');
		}

		//检查商品是否存在
		$issetgoods = Db::name('goods_specval')->where(['goods_id'=>$goods_id,'specval_id'=>$specval_id])->find();
		!$issetgoods && $this->error('商品不存在');

		//检查购物车是否存在该商品
		$incart = Db::name('user_cart')->where(['goods_id'=>$goods_id,'specval_id'=>$specval_id,'user_id'=>$uid,'addbyagent'=>0])->find();

		$id = 0;
		if ($incart) {
			if($num){
				$re = Db::name('user_cart')->where(['cart_id'=>$incart['cart_id']])->update(['num'=>$num]);
			}else{
				$re = Db::name('user_cart')->where(['cart_id'=>$incart['cart_id']])->setInc('num',1);
			}
			if ($re!==false) {
				$id = $incart['cart_id'];
			}
		}else{
			$data = [
				'user_id'    => $uid,
				'goods_id'   => $goods_id,
				'specval_id' => $specval_id,
				'add_time'   => date("Y-m-d h:i:s"),
				'shop_id'    => $this->user['shop_id'],
				'num'        => $num?:1
			];
			$id = Db::name('user_cart')->insertGetId($data);
		}
		if ($id) {
			$this->success('添加成功');
		}else{
			$this->error('添加失败');
		}
	}

	/**
	 * 删除
	 * @return [type] [description]
	 */
	public function del()
	{
		$uid = $this->uid;
		$cart_id = Request()->param('cart_id');

		empty($cart_id) && $this->error('缺少参数');
		$re = Db::name('user_cart')->where(['cart_id'=>['in',$cart_id]])->delete();
		if ($re) {
			$this->success('操作成功');
		}else{
			$this->error('操作失败');
		}
	}
}